package cn.tedu.mm.front.account.Service.impl;

import cn.tedu.mm.common.enumerator.ServiceCode;
import cn.tedu.mm.common.ex.ServiceException;
import cn.tedu.mm.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.mm.front.account.Service.IUserInfoService;
import cn.tedu.mm.front.account.dao.persist.repository.IUserInfoRepository;
import cn.tedu.mm.front.account.pojo.entity.UserInfo;
import cn.tedu.mm.front.account.pojo.param.UserUpdateInfoParam;
import cn.tedu.mm.front.account.pojo.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserInfoRepository userInfoRepository;
    @Override
    public UserInfoVO getUserInfo(Long id) {
        final UserInfoVO userInfo = userInfoRepository.getUserInfo(id);
        return userInfo;
    }

    @Override
    public void updatePassword(Long userId, String oldPassword, String newPassword) {
//        final Long userId = currentPrincipal.getId();
//        log.warn(""+userId);
        final UserInfoVO userInfo = userInfoRepository.getUserInfo(userId);
        String dbPassword=userInfo.getPassword();
        if (!passwordEncoder.matches(oldPassword,dbPassword)) {
            String message = "原密码错误，请重新输入！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        final String encodePassword = passwordEncoder.encode(newPassword);
        final UserInfo userInfo1 = new UserInfo();
        userInfo1.setId(userId);
        userInfo1.setPassword(encodePassword);
        final int rows = userInfoRepository.updatePassword(userInfo1);
        if (rows !=1) {
            String message = "修改密码失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

    }

    @Override
    public void updateInfo(UserUpdateInfoParam userUpdateInfoParam) {
        log.debug("开始处理【修改基本信息】的业务，当事人：{}，新基本信息：{}",  userUpdateInfoParam);
        final UserInfo userInfo = new UserInfo();
        final UserInfoVO userInfo1 = userInfoRepository.getUserInfo(userUpdateInfoParam.getId());
        if (userInfo1 == null) {
            String message = "用户不存在！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        BeanUtils.copyProperties(userUpdateInfoParam,userInfo);
        final int rows = userInfoRepository.updateInfo(userInfo);
        if (rows !=1) {
            String message = "修改错误！服务器繁忙，请稍后重试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }
}
